import axios from "axios";
import { getToken } from "./token";
import { Message } from "element-ui";

axios.defaults.baseURL = "http://127.0.0.1:8888/api/private/v1/";

//请求拦截器
axios.interceptors.request.use(
  function(config) {
    //在发送请求前
    config.headers.Authorization = getToken();
    return config;
  },
  function(error) {
    //请求错误
    return Promise.reject(error);
  }
);

//响应拦截器
axios.interceptors.response.use(
  function(response) {
    //响应数据
    if (
      response.data.meta.status !== 200 ||
      response.data.meta.status !== 201
    ) {
      Message({
        message: "请求失败!",
        type: "error",
        duration: 2000
      });
    }
    return response.data;
  },
  function(error) {
    Message({
      message: error.message,
      type: "error",
      duration: 2000
    });
    //响应数据错误
    return Promise.reject(error);
  }
);

export default axios; //直接返回axios;
